package com.hongtech.modules.generator.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hongtech.common.bean.AjaxResultVo;
import com.hongtech.modules.common.BaseController;
import com.hongtech.modules.generator.service.SysGeneratorService;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.hongtech.modules.generator.vo.TableListVO;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 代码生成器
 */
@Controller
@RequestMapping("/system/gen")
public class GeneratorController extends BaseController {

    @Autowired
    private SysGeneratorService sysGeneratorService;

    /**
     * 跳转日志页
     */
    @RequestMapping("/listGen")
    public String listGen() {
        return "system/gen/list";
    }

    /**
     * 列表
     */
    @ResponseBody
    @RequestMapping("/page")
    public AjaxResultVo page(String tableName, Integer offset, Integer limit) {
        PageHelper.startPage(getPageNo(limit, offset), limit);
        List<TableListVO> tableList = sysGeneratorService.queryList(tableName);
        PageInfo<TableListVO> pageData = new PageInfo<>(tableList);
        AjaxResultVo resultVo = AjaxResultVo.success();
        resultVo.put("total", pageData.getTotal());
        resultVo.put("rows", pageData.getList());
        return resultVo;
    }

    /**
     * 生成代码
     */
    @RequestMapping("/code")
    public void code(String tables, HttpServletResponse response) throws IOException {
        byte[] data = sysGeneratorService.generatorCode(tables.split(","));
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"hadmin.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}
